<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="家庭编码" prop="familyCode">
        <template #label>
          <Tooltip
            message="家庭编码在新增后自动生成"
            title="家庭编码"
          />
        </template>
        <el-input v-model="formData.familyCode" placeholder="请输入家庭编码" :disabled="true" />
      </el-form-item>
      <el-form-item label="家庭名称" prop="familyName">
        <el-input v-model="formData.familyName" placeholder="请输入家庭名称" />
      </el-form-item>
      <el-form-item label="邀请码" prop="familySharQr">
        <template #label>
          <Tooltip
            message="邀请码在新增后自动生成"
            title="邀请码"
          />
        </template>
        <div class="preview-container" @click="openDialog">
          <div v-if="qrcodeUrl" class="qrcode-preview">
            <img :src="qrcodeUrl" alt="二维码" class="qrcode-image" />
            <div class="preview-overlay">
              <el-icon><ZoomIn /></el-icon>
              <span>点击放大</span>
            </div>
          </div>
        </div>
<!--        <UploadImg v-model="formData.familySharQr" height="60px" width="60px" :disabled="true"/>-->
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="formData.status"
          placeholder="请选择状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.FAMILY_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <!-- 二维码放大弹窗 -->
  <el-dialog
    v-model="qrcodeDialogVisible"
    title="二维码预览"
    width="50%"
    :close-on-click-modal="false"
  >
    <div class="dialog-content">
      <div v-if="qrcodeUrl" class="qrcode-dialog">
        <img :src="qrcodeUrl" alt="二维码" class="qrcode-dialog-image" />
        <div class="dialog-actions">
          <el-button type="primary" :icon="Download" @click="downloadQRCode">
            下载二维码
          </el-button>
          <el-button @click="qrcodeDialogVisible = false">关闭</el-button>
        </div>
      </div>
      <div v-else class="empty-dialog">
        <el-icon :size="60"><Picture /></el-icon>
        <p>暂无二维码可显示</p>
      </div>
    </div>
  </el-dialog>
</template>
<script setup lang="ts">
import { FamilyApi, FamilyVO } from '@/api/remind/family'
import {DICT_TYPE, getIntDictOptions} from "@/utils/dict";
import QRCode from 'qrcode'
import {Download, ZoomIn} from "@element-plus/icons-vue";

/** 家庭 表单 */
defineOptions({ name: 'FamilyForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  familyCode: undefined,
  familyName: undefined,
  familySharQr: undefined,
  status: undefined,
})
const formRules = reactive({
  familyCode: [{ required: false, message: '家庭邀请码不能为空', trigger: 'blur' }],
  familyName: [{ required: true, message: '家庭名称不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await FamilyApi.getFamily(id)
      await generateQRCode()
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as FamilyVO
    if (formType.value === 'create') {
      await FamilyApi.createFamily(data)
      message.success(t('common.createSuccess'))
    } else {
      await FamilyApi.updateFamily(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

// 二维码数据URL
const qrcodeUrl = ref('')

// 弹窗显示控制
const qrcodeDialogVisible = ref(false)

// 生成二维码
const generateQRCode = async () => {
  if (!formData.value.familyCode) {
    qrcodeUrl.value = ''
    return
  }

  try {
    qrcodeUrl.value = await QRCode.toDataURL(formData.value.familyCode, {
      width: 200,
      margin: 1,
      color: {
        dark: '#000000',
        light: '#ffffff'
      }
    })
  } catch (err) {
    console.error('生成二维码失败:', err)
    message.error('生成二维码失败，请重试')
  }
}

// 打开弹窗
const openDialog = () => {
  if (!qrcodeUrl.value) {
    message.warning('请先生成二维码')
    return
  }
  qrcodeDialogVisible.value = true
}

// 下载二维码
const downloadQRCode = async () => {
  if (!qrcodeUrl.value) return

  try {
    // 创建下载链接
    const link = document.createElement('a')
    link.href = qrcodeUrl.value
    link.download = `qrcode_${Date.now()}.png`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

    message.success('二维码下载成功')
  } catch (err) {
    console.error('下载二维码失败:', err)
    message.error('下载二维码失败')
  }
}

// 组件挂载时生成默认二维码
onMounted(() => {
  generateQRCode()
})

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    familyCode: undefined,
    familyName: undefined,
    familySharQr: undefined,
    status: undefined,
  }
  formRef.value?.resetFields()
}
</script>
<style scoped lang="scss">
.preview-container {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 220px;
  cursor: pointer;
  border: 1px dashed #dcdfe6;
  border-radius: 6px;
  padding: 20px;
  transition: border-color 0.3s;
}

.preview-container:hover {
  border-color: #409eff;
}

.qrcode-preview {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}

.qrcode-image {
  max-width: 100%;
  max-height: 200px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.preview-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: white;
  opacity: 0;
  transition: opacity 0.3s;
  border-radius: 4px;
}

.preview-overlay .el-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

.qrcode-preview:hover .preview-overlay {
  opacity: 1;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #909399;
  gap: 12px;
}

.dialog-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px;
}

.qrcode-dialog {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.qrcode-dialog-image {
  max-width: 100%;
  max-height: 400px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
  background: white;
}

.dialog-actions {
  display: flex;
  gap: 10px;
  justify-content: center;
}

.empty-dialog {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #909399;
  gap: 15px;
  padding: 40px 0;
}
</style>
